package com.leo.foodmaster.commons.util;

import cn.hutool.core.bean.BeanUtil;
import com.leo.foodmaster.admin.system.entity.UserBean;
import com.leo.foodmaster.commons.constants.AuthConstants;
import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * 网络请求工具类：从请求中获取用户信息
 * </p>
 *
 * @author ：Leo
 * @since ：2021-06-24 10:14
 */
@UtilityClass
@Slf4j
public class WebUtils {

    /**
     * 获取请求
     * @return HttpServletRequest
     */
    public HttpServletRequest getRequest(){
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        assert requestAttributes != null;
        return requestAttributes.getRequest();
    }


    /**
     * 从请求中获取登录用户
     * @return UserBean
     */
    public UserBean getUser(){
        try {
            Object attribute = getRequest().getAttribute(AuthConstants.USER_INFO);
            if(attribute == null){
                return null;
            }
            UserBean user = new UserBean();
            BeanUtil.copyProperties(attribute, user);
            return user;
        }catch (Exception e){
            log.info("未取得用户信息:"+e.getMessage());
            return null;
        }
    }
}
